package com.example.idlefish.HomeAndSearch

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.telecom.Call


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.ApplicationConst.NetRequestForGoodContext
import com.example.idlefish.R
import okhttp3.Response
import java.io.IOException
import okhttp3.Callback
import org.bouncycastle.util.encoders.Base64
import org.json.JSONObject
import java.util.concurrent.CopyOnWriteArrayList

class GoodsAdapater (


    private val items: CopyOnWriteArrayList<ProductInfo>, // 数据源
    private val onItemClick: (Int) -> Unit, // 点击事件回调
    private val recyclerView: RecyclerView,
    ) : RecyclerView.Adapter<GoodsAdapater.GoodsViewHolder>() {
    class GoodsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        //val tvchoice: TextView = itemView.findViewById(R.id.tvchoice) // 假设布局中有一个 TextView
        val goods_id : TextView = itemView.findViewById(R.id.goods_id)
        val goods_prize : TextView = itemView.findViewById(R.id.goods_prize)
        val saler_name : TextView = itemView.findViewById(R.id.saler_name)
        val advantage : TextView = itemView.findViewById(R.id.advantage)
        val sold : TextView = itemView.findViewById(R.id.sold)
        val picture : ImageView = itemView.findViewById(R.id.goods_picture)
        val one : LinearLayout = itemView.findViewById(R.id.goods_one)
        val cut: LinearLayout = itemView.findViewById(R.id.cut)
        val cutimage : ImageView = itemView.findViewById(R.id.cutimage)
        val saler_pic : ImageView = itemView.findViewById(R.id.saler_pic)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodsAdapater.GoodsViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.one_goods, parent, false)
        val viewHolder = GoodsViewHolder(view)
        return viewHolder
    }

    override fun onBindViewHolder(holder: GoodsViewHolder, position: Int) {
        val item = items[position]
        holder.goods_id.text = item.text
        holder.goods_prize.text = item.price.toString()
        holder.saler_name.text = item.address
        holder.advantage.text = item.advantage
        holder.sold.text = item.wanting.toString() + "想要"
        if(item.cut == 1)
        {
            holder.cut.visibility = View.VISIBLE // 数据为0，显示TextVie
            val originalBitmap = BitmapFactory.decodeResource(holder.itemView.context.resources, R.drawable.cut)
            val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 20, 20, true)

            // 设置缩放后的图片
            holder.cutimage.setImageBitmap(scaledBitmap)
            }
        else
        {
            holder.cut.visibility = View.GONE
        }
        NetRequestForGoodContext(item.id.toLong(),  object : Callback {
            // 实现 onFailure 方法

            override fun onFailure(call: okhttp3.Call, e: IOException) {
                println("请求失败: ${e.message}")
            }

            override fun onResponse(call: okhttp3.Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) {
                        // 如果响应失败，输出状态码
                        println("请求失败，状态码: ${response.code}")
                        return
                    }

                    // 输出响应体内容
                    val responseBody = response.body?.string()
                    println("请求成功，响应内容: $responseBody")
                    if (responseBody != null) {
                        try {
                            // 将响应体字符串解析为 JSON 对象
                            val jsonObject = JSONObject(responseBody)

                            val queryGoodResponse = jsonObject.getJSONObject("queryGoodResponse")
                            val picEncodingList = queryGoodResponse.getJSONArray("picEncodeingList")
                            println(picEncodingList)
                            val bitmap = ApplicationConst.decodeBase64ToImage(holder.itemView.context,picEncodingList.get(0).toString())
                            if (bitmap != null) {
                                (holder.itemView.context as Activity).runOnUiThread {
                                    holder.picture.setImageBitmap(bitmap)
                                }
                            }
                        } catch (e: Exception) {
                            println("解析 JSON 失败: ${e.message}")
                        }
                    }
                }
            }
        })


        NetRequestForGoodContext(item.id.toLong(),  object : Callback {
            // 实现 onFailure 方法

            override fun onFailure(call: okhttp3.Call, e: IOException) {
                println("请求失败: ${e.message}")
            }

            override fun onResponse(call: okhttp3.Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) {
                        // 如果响应失败，输出状态码
                        println("请求失败，状态码: ${response.code}")
                        return
                    }

                    // 输出响应体内容
                    val responseBody = response.body?.string()
                    println("请求成功，响应内容: $responseBody")
                    if (responseBody != null) {
                        try {
                            // 将响应体字符串解析为 JSON 对象
                            val jsonObject = JSONObject(responseBody)

                            val querySellerResponse = jsonObject.getJSONObject("querySellerResponse")
                            val sellerAvatar = querySellerResponse.getString("avatar63Code")
                            val avatarByte = Base64.decode(sellerAvatar)
                            val options = BitmapFactory.Options().apply {
                                inSampleSize = 4 // 将图片宽高缩小一半
                            }
                            val avatarBitmap = BitmapFactory.decodeByteArray(avatarByte, 0, avatarByte.size, options)
                            if (avatarBitmap != null) {
                                (holder.itemView.context as Activity).runOnUiThread {
                                    holder.saler_pic.setImageBitmap(avatarBitmap)
                                }
                            }
                            val queryGoodResponse = jsonObject.getJSONObject("queryGoodResponse")
                            val picEncodingList = queryGoodResponse.getJSONArray("picEncodeingList")
                            println(picEncodingList)
                            val bitmap = ApplicationConst.decodeBase64ToImage(holder.itemView.context,picEncodingList.get(0).toString())
                            if (bitmap != null) {
                                (holder.itemView.context as Activity).runOnUiThread {
                                    holder.picture.setImageBitmap(bitmap)
                                }
                            }
                        } catch (e: Exception) {
                            println("解析 JSON 失败: ${e.message}")
                        }
                    }
                }
            }
        })


        holder.itemView.setOnClickListener {
            val itemId = item.id
            onItemClick(itemId) }
    }

    override fun getItemCount(): Int = items.size

}